<template>
  <div class="chapter-preview-app">
    <!-- Header -->
    <AppHeader 
      :current-user="currentUser"
      :show-search="false"
      @login="showLoginModal"
      @register="showRegisterModal"
      @logout="handleLogout"
    />

    <!-- Breadcrumb Navigation -->
    <nav class="breadcrumb-nav">
      <div class="breadcrumb-content">
        <div class="breadcrumb">
          <router-link to="/" class="breadcrumb-item">
            <i class="fas fa-home"></i>
            笔记中心
          </router-link>
          <router-link 
            v-if="course"
            :to="{ name: 'CoursePreview', query: { courseId: course.id } }" 
            class="breadcrumb-item"
          >
            {{ course.name }}
          </router-link>
          <span class="breadcrumb-item" v-if="chapter">{{ chapter.title }}</span>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
      <!-- Loading State -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>正在加载章节信息...</p>
      </div>

      <!-- Error State -->
      <div v-else-if="error" class="error-state">
        <i class="fas fa-exclamation-triangle"></i>
        <h2>加载失败</h2>
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="loadChapter">
          <i class="fas fa-redo"></i>
          重新加载
        </button>
      </div>

      <!-- Chapter Content -->
      <div v-else-if="chapter" class="chapter-details">
        <!-- Chapter Header -->
        <div class="chapter-header">
          <div class="chapter-info">
            <h1 class="chapter-title">{{ chapter.title || '未命名章节' }}</h1>
            <div class="chapter-meta">
              <div class="meta-item">
                <i class="fas fa-book"></i>
                <span>来自：{{ course?.name }}</span>
              </div>
              <div class="meta-item">
                <i class="fas fa-clock"></i>
                <span>创建于 {{ formatDate(chapter.createdAt) }}</span>
              </div>
              <div class="meta-item" v-if="chapter.lastModified">
                <i class="fas fa-edit"></i>
                <span>更新于 {{ formatDate(chapter.lastModified) }}</span>
              </div>
            </div>
          </div>
          <div class="chapter-actions">
            <router-link 
              :to="{ name: 'Course', query: { courseId: course.id } }" 
              class="btn btn-primary"
              v-if="currentUser && currentUser.id === course.userId"
            >
              <i class="fas fa-edit"></i>
              编辑章节
            </router-link>
            <button class="btn btn-outline" @click="shareChapter">
              <i class="fas fa-share"></i>
              分享
            </button>
          </div>
        </div>

        <!-- Chapter Content -->
        <div class="chapter-content">
          <div class="content-container" v-html="chapter.content"></div>
        </div>

        <!-- Chapter Navigation -->
        <div class="chapter-navigation" v-if="course && course.chapters">
          <div class="nav-item">
            <button 
              v-if="previousChapter"
              class="btn btn-outline"
              @click="navigateToChapter(previousChapter)"
            >
              <i class="fas fa-chevron-left"></i>
              上一章节：{{ previousChapter.title }}
            </button>
          </div>
          <div class="nav-item">
            <router-link 
              :to="{ name: 'CoursePreview', query: { courseId: course.id } }" 
              class="btn btn-ghost"
            >
              <i class="fas fa-list"></i>
              章节列表
            </router-link>
          </div>
          <div class="nav-item">
            <button 
              v-if="nextChapter"
              class="btn btn-outline"
              @click="navigateToChapter(nextChapter)"
            >
              下一章节：{{ nextChapter.title }}
              <i class="fas fa-chevron-right"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- Chapter Not Found -->
      <div v-else class="chapter-not-found">
        <i class="fas fa-exclamation-triangle"></i>
        <h2>章节不存在</h2>
        <p>您要查看的章节不存在或已被删除</p>
        <router-link to="/" class="btn btn-primary">
          <i class="fas fa-home"></i>
          返回首页
        </router-link>
      </div>
    </main>
  </div>
</template>

<script>
import AppHeader from '@/components/AppHeader.vue'
import apiService from '@/services/api.js'

export default {
  name: 'ChapterPreviewPage',
  components: {
    AppHeader
  },
  data() {
    return {
      course: null,
      chapter: null,
      currentUser: null,
      loading: false,
      error: null
    }
  },
  computed: {
    currentChapterIndex() {
      if (!this.course || !this.course.chapters || !this.chapter) return -1
      return this.course.chapters.findIndex(c => c.id === this.chapter.id)
    },
    previousChapter() {
      if (this.currentChapterIndex <= 0) return null
      return this.course.chapters[this.currentChapterIndex - 1]
    },
    nextChapter() {
      if (this.currentChapterIndex >= this.course.chapters.length - 1) return null
      return this.course.chapters[this.currentChapterIndex + 1]
    }
  },
  mounted() {
    this.loadChapter()
    this.checkAuthStatus()
  },
  watch: {
    '$route.query': {
      handler() {
        this.loadChapter()
      },
      deep: true
    }
  },
  methods: {
    async loadChapter() {
      const courseId = this.$route.query.courseId
      const chapterId = this.$route.query.chapterId
      
      if (courseId && chapterId) {
        this.loading = true
        this.error = null
        try {
          // 调用后端 API 获取课程详情（包含所有章节）
          const response = await apiService.getCourse(courseId)
          if (response.success) {
            // 后端返回的数据结构是 {success, data: {course}}
            // 我们需要提取 course 并赋值给 this.course
            this.course = response.course || response.data
            
            // 从课程的章节中找到指定的章节
            if (this.course && this.course.chapters) {
              this.chapter = this.course.chapters.find(ch => ch.id == chapterId)
              if (!this.chapter) {
                this.error = '章节不存在'
              }
            } else {
              this.error = '课程数据不完整'
            }
          } else {
            this.error = response.message || '获取课程信息失败'
          }
        } catch (error) {
          console.error('获取课程信息失败:', error)
          this.error = '获取课程信息失败: ' + (error.message || '未知错误')
        } finally {
          this.loading = false
        }
      }
    },
    checkAuthStatus() {
      const savedUser = localStorage.getItem('currentUser')
      if (savedUser) {
        this.currentUser = JSON.parse(savedUser)
      }
    },
    navigateToChapter(chapter) {
      this.$router.push({
        name: 'ChapterPreview',
        query: {
          courseId: this.course.id,
          chapterId: chapter.id
        }
      })
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    },
    shareChapter() {
      if (navigator.share) {
        navigator.share({
          title: this.chapter.title,
          text: `来自笔记"${this.course.name}"的章节`,
          url: window.location.href
        })
      } else {
        // Fallback: copy to clipboard
        navigator.clipboard.writeText(window.location.href).then(() => {
          this.showAlert('链接已复制到剪贴板', 'success')
        })
      }
    },
    showAlert(message, type) {
      // Simple alert implementation
      const alertDiv = document.createElement('div')
      alertDiv.className = `alert alert-${type}`
      alertDiv.textContent = message
      alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 1rem 1.5rem;
        border-radius: 6px;
        color: white;
        font-size: 12px;
        z-index: 10000;
        background: ${type === 'success' ? '#10b981' : '#ef4444'};
      `
      
      document.body.appendChild(alertDiv)
      
      setTimeout(() => {
        if (alertDiv.parentNode) {
          alertDiv.parentNode.removeChild(alertDiv)
        }
      }, 3000)
    },
    showLoginModal() {
      // Handle login modal
    },
    showRegisterModal() {
      // Handle register modal
    },
    handleLogout() {
      this.currentUser = null
      localStorage.removeItem('currentUser')
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.chapter-preview-app {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8fafc;
}

/* Loading State */
.loading-state {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e2e8f0;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  font-size: 12px;
  color: #64748b;
  margin: 0;
}

/* Error State */
.error-state {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.error-state i {
  font-size: 64px;
  color: #fbbf24;
  margin-bottom: 1rem;
}

.error-state h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.error-state p {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 2rem;
}

/* Breadcrumb Navigation */
.breadcrumb-nav {
  background: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0.75rem 0;
}

.breadcrumb-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 2rem;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: inherit;
  text-decoration: none;
}

.breadcrumb-item:hover {
  color: #3b82f6;
}

.breadcrumb-item:not(:last-child)::after {
  content: '/';
  margin-left: 0.5rem;
  color: #cbd5e1;
}

/* Main Content */
.main-content {
  flex: 1;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  padding: 2rem;
}

.chapter-details {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* Chapter Header */
.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 2rem;
  border-bottom: 1px solid #e2e8f0;
  gap: 2rem;
}

.chapter-info {
  flex: 1;
}

.chapter-title {
  font-size: 28px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 1rem;
  line-height: 1.3;
}

.chapter-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 12px;
  color: #64748b;
}

.meta-item i {
  color: #94a3b8;
}

.chapter-actions {
  display: flex;
  gap: 1rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  border: 1px solid transparent;
}

.btn-primary {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.btn-outline {
  background: transparent;
  color: #64748b;
  border-color: #e2e8f0;
}

.btn-outline:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.btn-ghost {
  background: transparent;
  color: #64748b;
  border-color: transparent;
}

.btn-ghost:hover {
  background: #f8fafc;
  color: #1e293b;
}

/* Chapter Content */
.chapter-content {
  padding: 2rem;
}

.content-container {
  font-size: 16px;
  line-height: 1.8;
  color: #1e293b;
  max-width: none;
}

.content-container :deep(h1),
.content-container :deep(h2),
.content-container :deep(h3),
.content-container :deep(h4),
.content-container :deep(h5),
.content-container :deep(h6) {
  font-weight: 600;
  margin-top: 2rem;
  margin-bottom: 1rem;
  color: #1e293b;
}

.content-container :deep(h1) {
  font-size: 2rem;
}

.content-container :deep(h2) {
  font-size: 1.5rem;
}

.content-container :deep(h3) {
  font-size: 1.25rem;
}

.content-container :deep(p) {
  margin-bottom: 1.5rem;
}

.content-container :deep(ul),
.content-container :deep(ol) {
  margin-bottom: 1.5rem;
  padding-left: 2rem;
}

.content-container :deep(li) {
  margin-bottom: 0.5rem;
}

.content-container :deep(blockquote) {
  margin: 1.5rem 0;
  padding: 1rem 1.5rem;
  border-left: 4px solid #3b82f6;
  background: #f8fafc;
  color: #64748b;
  font-style: italic;
}

.content-container :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 1.5rem 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.content-container :deep(code) {
  background: #f1f5f9;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 0.875em;
  color: #ec4899;
}

.content-container :deep(pre) {
  background: #1e293b;
  color: #f1f5f9;
  padding: 1.5rem;
  border-radius: 8px;
  overflow-x: auto;
  margin: 1.5rem 0;
}

.content-container :deep(pre code) {
  background: none;
  padding: 0;
  color: inherit;
}

/* Chapter Navigation */
.chapter-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-top: 1px solid #e2e8f0;
  gap: 1rem;
}

.nav-item {
  flex: 1;
}

.nav-item:first-child {
  text-align: left;
}

.nav-item:nth-child(2) {
  text-align: center;
}

.nav-item:last-child {
  text-align: right;
}

.nav-item .btn {
  padding: 0.5rem 1rem;
  font-size: 11px;
}

/* Empty State */
.chapter-not-found {
  text-align: center;
  padding: 3rem 2rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chapter-not-found i {
  font-size: 48px;
  color: #cbd5e1;
  margin-bottom: 1rem;
}

.chapter-not-found h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.chapter-not-found p {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 2rem;
}

@media (max-width: 768px) {
  .main-content {
    padding: 1rem;
  }
  
  .chapter-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .chapter-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .chapter-title {
    font-size: 24px;
  }
  
  .chapter-navigation {
    flex-direction: column;
    gap: 1rem;
  }
  
  .nav-item {
    text-align: center !important;
  }
  
  .content-container {
    font-size: 14px;
  }
}
</style>